package com.example.toutiao;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;

import com.example.toutiao.ui.fragment.HeadlinesFragment;
import com.example.toutiao.ui.fragment.MallFragment;
import com.example.toutiao.ui.fragment.ProfileFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView bottomNavigationView;
    private String currentUsername;

    @SuppressLint({"NonConstantResourceId","MissingInflatedId"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        currentUsername = getIntent().getStringExtra("username");
        TextView tabBarTitle = findViewById(R.id.tabBarTitle);
        bottomNavigationView = findViewById(R.id.bottom_nav);
        loadFragment(new HeadlinesFragment()); // 默认首页是头条
        tabBarTitle.setText("头条");
        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            Fragment selectedFragment = null;

            if (item.getItemId() == R.id.nav_headlines) {
                selectedFragment = new HeadlinesFragment();
                tabBarTitle.setText("头条");
            } else if (item.getItemId() == R.id.nav_mall) {
                selectedFragment = new MallFragment();
                tabBarTitle.setText("商城");
            } else if (item.getItemId() == R.id.nav_profile) {
                selectedFragment = ProfileFragment.newInstance(currentUsername); // 传用户
                tabBarTitle.setText("我的");
            }

            return loadFragment(selectedFragment);
        });
    }

    private boolean loadFragment(Fragment fragment) {
        if (fragment != null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, fragment)
                    .commit();
            return true;
        }
        return false;
    }
}
